//
//  UIColor+AP.swift
//  APExtensions
//
//  Created by jianbo.pei on 2023/6/25.
//

import Foundation
import UIKit

extension UIColor {
    convenience init(r: Int, g: Int, b: Int) {
        self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1.0)
    }
    
    convenience init(hex: String, alpha: CGFloat = 1.0) {
        var uppercasedHex = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
        if uppercasedHex.contains("#") {
            uppercasedHex.remove(at: uppercasedHex.startIndex)
        }
        if uppercasedHex.count == 6 || uppercasedHex.count == 8 {
            var rgbValue: UInt64 = 0
            Scanner(string: uppercasedHex).scanHexInt64(&rgbValue)
            self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
                      green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
                      blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
                      alpha: alpha)
        } else {
            self.init()
        }
    }
}

extension UIColor : APCompatible {}
public extension APBase where Base: UIColor {
    static func rgba(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> UIColor {
        return UIColor(red: r, green: g, blue: b, alpha: a)
    }
    
    static func ra(r: CGFloat, a: CGFloat) -> UIColor {
        return UIColor(red: r, green: r, blue: r, alpha: a)
    }
    
    static func rgb(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
        return UIColor(red: r, green: g, blue: b, alpha: 1.0)
    }
    
    static var random: UIColor {
        let r = CGFloat(arc4random() % 256) / 255.0
        let g = CGFloat(arc4random() % 256) / 255.0
        let b = CGFloat(arc4random() % 256) / 255.0
        return UIColor(red: r, green: g, blue: b, alpha: 1.0)
    }
    
    static func hex(_ hex: String, alpha: CGFloat = 1.0) -> UIColor {
        UIColor(hex: hex, alpha: alpha)
    }
}
